package com.bibi.zoo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

/**
 * @Author: Wu Shenzhuang
 * @Date: 2019/5/9 13:57
 */
@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {

    //实现ScheduledTaskRegistrar中的configureTasks方法，设置调度器
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = setTaskExecutors();
        //设置任务注册器的调度器
        scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
    }
    @Bean(destroyMethod = "shutdown")
    public ThreadPoolTaskScheduler setTaskExecutors(){
        //创建一个线程池调度器
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        //设置线程池容量
        scheduler.setPoolSize(4);
        //线程名前缀
        scheduler.setThreadNamePrefix("task-");
        //等待时常
        scheduler.setAwaitTerminationSeconds(60);
        //当调度器shutdown被调用时等待当前被调度的任务完成
        scheduler.setWaitForTasksToCompleteOnShutdown(true);
        //设置当任务被取消的同时从当前调度器移除的策略
        scheduler.setRemoveOnCancelPolicy(true);
        return scheduler;
    }
}
